﻿using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("api/[controller]")]
public class ProtectedController : ControllerBase
{
    private readonly ILogger<ProtectedController> _logger;

    public ProtectedController(ILogger<ProtectedController> logger)
    {
        _logger = logger;
    }

    [HttpGet("user-info")]
    public IActionResult GetUserInfo()
    {
        // 从HttpContext Items获取用户信息（由中间件设置）
        var userSession = HttpContext.Items["UserSession"] as UserSession;
        var userInfo = HttpContext.Items["UserInfo"] as WeChatUserInfo;

        if (userSession == null)
        {
            return Unauthorized(new { code = 401, message = "未授权访问" });
        }

        return Ok(new
        {
            openId = userSession.OpenId,
            nickName = userInfo?.NickName,
            avatar = userInfo?.HeadImgUrl,
            loginTime = userSession.CreatedAt,
            lastAccessTime = userSession.LastAccessedAt,
            expiresAt = userSession.ExpiresAt,
            isAuthenticated = true
        });
    }

    [HttpGet("data")]
    public IActionResult GetProtectedData()
    {
        var userSession = HttpContext.Items["UserSession"] as UserSession;
        var userInfo = HttpContext.Items["UserInfo"] as WeChatUserInfo;

        if (userSession == null)
        {
            return Unauthorized(new { code = 401, message = "未授权访问" });
        }

        // 只有认证用户才能访问的数据
        return Ok(new
        {
            data = "这是受保护的数据",
            timestamp = DateTime.UtcNow,
            user = new
            {
                openId = userSession.OpenId,
                nickName = userInfo?.NickName,
                avatar = userInfo?.HeadImgUrl
            },
            sessionInfo = new
            {
                created = userSession.CreatedAt,
                lastAccessed = userSession.LastAccessedAt,
                expires = userSession.ExpiresAt
            }
        });
    }
}